const router = require('koa-router')()
const util = require('../utils/util')
const Notice = require('../models/noticeSchema')

// 定义路由前缀
router.prefix('/notice')

// 获取公告数据
router.get('/list', async (ctx) => {
  try {
    let noticeList;
    const type = ctx.request.query.type;
    // 没有提供type，则查找所有公告
    if (!type) {
      noticeList = await Notice.find({})
    } else {
      // 提供了type,则根据type来查找公告
      noticeList = await Notice.find({ noticeType: type })
    }
    ctx.body = util.success(noticeList)

  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})

// 公告 创建/编辑/删除
router.post('/operate', async (ctx) => {
  const { action, ...params } = ctx.request.body
  let res, info;
  try {
    if (action == 'add') {
      await Notice.create(params)
      info = '创建成功'
    } else if (action == 'edit') {
      params.createTime = new Date()
      await Notice.findOneAndUpdate(userName, params)
      info = '编辑成功'
    } else if (action == 'delete') {
      await Notice.findOneAndDelete(userName)
      info = '删除成功'
    }
    ctx.body = util.success('', info)
  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})

module.exports = router